<?php

namespace app\uni\controller;

use think\Controller;
use EasyWeChat\Factory;

class Business extends Controller
{
    protected $BusinessModel = null;
    protected $weChat = null;
    protected $OrderProductModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('business.Business');
        $this->OrderProductModel = model('product.order.Product');

        $this->weChat = Factory::miniProgram([
            'app_id' => config('site.appid'),
            'secret' => config('site.secret'),
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            // 日志
            'log' => [
                'level' => 'debug',
                'file' => LOG_PATH . '/weChat.log',
            ]
        ]);
    }


    //登录
    public function login()
    {
        //登录
        if ($this->request->isPost()) {
            $code = $this->request->param('code', '', 'trim');

            if (empty($code)) {
                $this->error('获取临时登录凭证失败');
            }

            $session = $this->weChat->auth->session($code);

            // 每个用户唯一标识
            $openid = $session['openid'] ?? '';

            if (empty($openid)) {
                $this->error('获取登录凭证失败');
            }

            $business = $this->BusinessModel->where(['openid' => $openid])->find();

            if ($business) {
                // 返回信息
                $data = [
                    'id' => $business['id'],
                    'mobile' => $business['mobile'],
                    'nickname' => $business['nickname'],
                    'email' => $business['email'],
                    'gender' => $business['gender'],
                    'gender_text' => $business['gender_text'],
                    'province' => $business['province'],
                    'city' => $business['city'],
                    'district' => $business['district'],
                    'region_text' => $business['region_text'],
                    'auth' => $business['auth'],
                    'avatar_cdn' => $business['avatar_cdn'],
                    'createtime_text' => $business['createtime_text'],
                    'openid' => $business['openid']
                ];

                $this->success("绑定账号成功", null, $data);
            } else {
                $this->error('请先绑定微信账号', null, ['openid' => $openid]);
            }
        }
    }

    //注册
    public function bind()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $openid = $this->request->param('openid', '', 'trim');

            if (empty($openid)) {
                $this->error('获取登录凭证失败');
            }

            $openidStatus = $this->BusinessModel->where(['openid' => $openid])->find();

            if ($openidStatus) {
                $this->error('该微信账号已绑定其他账号');
            }

            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if ($business) {
                // 直接绑定

                // 判断密码是否正确
                $repass = md5($password . $business['salt']);

                if ($repass !== $business['password']) {
                    $this->error('密码错误');
                }

                $data = [
                    'id' => $business['id'],
                    'openid' => $openid
                ];

                $result = $this->BusinessModel->isUpdate(true)->save($data);
            } else {
                // 注册 + 绑定

                // 生成密码盐
                $salt = build_randstr();

                $password = md5($password . $salt);

                $sourceid = model('business.Source')->where(['name' => ['LIKE', "%防伪溯源查询%"]])->value('id');

                $data = [
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile, 3, 4),
                    'salt' => $salt,
                    'password' => $password,
                    'sourceid' => $sourceid,
                    'openid' => $openid,
                ];

                $result = $this->BusinessModel->validate('common/business/Business')->save($data);
            }

            if ($result === false) {
                $this->error($this->BusinessModel->getError());
            } else {
                $this->success("绑定微信账号成功");
            }
        }
    }


    //H5端登录
    public function web()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

            if ($business) {
                // 直接绑定

                // 判断密码是否正确
                $repass = md5($password . $business['salt']);

                if ($repass !== $business['password']) {
                    $this->error('密码错误');
                }

                // 返回信息
                $data = [
                    'id' => $business['id'],
                    'mobile' => $business['mobile'],
                    'nickname' => $business['nickname'],
                    'email' => $business['email'],
                    'gender' => $business['gender'],
                    'gender_text' => $business['gender_text'],
                    'province' => $business['province'],
                    'city' => $business['city'],
                    'district' => $business['district'],
                    'region_text' => $business['region_text'],
                    'auth' => $business['auth'],
                    'avatar_cdn' => $business['avatar_cdn'],
                    'createtime_text' => $business['createtime_text'],
                    'openid' => $business['openid']
                ];

                $this->success("登录成功", null, $data);
            } else {
                $salt = build_randstr();

                $password = md5($password . $salt);

                $sourceid = model('business.Source')->where(['name' => ['LIKE', "%防伪溯源查询%"]])->value('id');

                $data = [
                    'mobile' => $mobile,
                    'nickname' => build_encrypt($mobile, 3, 4),
                    'password' => $password,
                    'salt' => $salt,
                    'sourceid' => $sourceid
                ];

                $result = $this->BusinessModel->validate('common/business/Business')->save($data);

                if ($result === false) {
                    $this->error($this->BusinessModel->getError());
                } else {
                    $business = $this->BusinessModel->find($this->BusinessModel->id);

                    // 返回信息
                    $info = [
                        'id' => $business['id'],
                        'mobile' => $business['mobile'],
                        'nickname' => $business['nickname'],
                        'email' => $business['email'],
                        'gender' => $business['gender'],
                        'gender_text' => $business['gender_text'],
                        'province' => $business['province'],
                        'city' => $business['city'],
                        'district' => $business['district'],
                        'region_text' => $business['region_text'],
                        'auth' => $business['auth'],
                        'avatar_cdn' => $business['avatar_cdn'],
                        'createtime_text' => $business['createtime_text'],
                        'openid' => $business['openid']
                    ];

                    $this->success('登录成功', null, $info);
                }
            }
        }
    }

    //解绑账号
    public function unbind()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', '', 'trim');

            $business = $this->BusinessModel->where(['id' => $busid])->find();

            if (!$business) {
                $this->error('用户不存在');
            }

            $data = [
                'id' => $busid,
                'openid' => null
            ];

            $result = $this->BusinessModel->isUpdate(true)->save($data);

            if ($result === false) {
                $this->error('解除微信绑定失败');
            } else {
                $this->success('解除微信绑定成功');
            }
        }
    }

    //查询商品
    public function product()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $where = [
                'busid' => $busid,
            ];

            if (!empty($keyword)) {
                $where['products.name'] = ['LIKE', "%$keyword%"];
            }

            $list = $this->OrderProductModel->with(['products'])->where($where)->page($page, $limit)->order('id desc')->select();

            if ($list) {
                $this->success('查询成功', null, $list);
            } else {
                $this->error('暂无商品', null, $list);
            }
        }
    }

    //创建二维码
    public function generate()
    {
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $product = $this->OrderProductModel->with(['products'])->where(['code' => $code])->find();

            if(!$product)
            {
                $this->error('防伪码产品不存在');
            }

            $path = "/pages/validate/info?code=$code";

            //生成二维码
            $response = $this->weChat->app_code->get($path);

            $data = [
                'id' => $product['id'],// 订单商品id
            ];

            //保存二维码到文件中        
            if($response instanceof \EasyWeChat\Kernel\Http\StreamResponse)
            {
                $filename = $response->saveAs(ROOT_PATH . '/public/uploads/wxcode', "{$code}.png");

                if($filename)
                {
                    $data['query_qrcode'] = '/uploads/wxcode/' . $filename;
                }
            }

            $result = $this->OrderProductModel->isUpdate(true)->save($data);

            if($result === false)
            {
                $this->error('生成防伪码失败');
            }else{

                $product = $this->OrderProductModel->with(['products'])->where(['code' => $code])->find();

                $this->success('生成防伪码成功',null,$product);
            }

        }
    }

    //跳转到防伪码页面info
    public function info(){
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', '', 'trim');
            $code = $this->request->param('code', '', 'trim');

            $business = $this->BusinessModel->find($busid);

            if (!$business) {
                $this->error('用户不存在');
            }

            $product = $this->OrderProductModel->with(['products'])->where(['code' => $code])->find();

            if(!$product)
            {
                $this->error('防伪码产品不存在');
            }

            $data = [
                'id' => $product['id'],
                'num' => $product['num'] ? bcadd($product['num'],1) : 1
            ];

            if(empty($product['num']) && empty($product['querytime']))
            {
                $data['querytime'] = time();
            }

            $this->OrderProductModel->isUpdate(true)->save($data);

            $product = $this->OrderProductModel->with(['products'])->where(['code' => $code])->find();

            $this->success('查询数据成功',null,$product);

        }
    }
}
